<template>
  <div class="register-div">
    <el-form
      key="ds"
      :model="registerForm"
      ref="registerForm"
      :rules="rules"
      class="register-form"
      autocomplete="off"
      label-position="right"
    >
      <div class="title">
        <span class="title-icon">
          <svg-icon style="width: 40px;height: 40px;" name="icon_sign" />
        </span>
        <span>新用户注册</span>
      </div>
      <el-row :gutter="24" type="flex" style="flex-wrap:wrap" align="middle">
        <el-col :span="12">
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              type="text"
              autocomplete="off"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon name="icon_user" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="姓名"
              type="text"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon name="icon_user" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="mobile">
            <el-input
              v-model="registerForm.mobile"
              placeholder="手机号码"
              maxlength="11"
              type="text"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon name="icon_phone" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              type="text"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon style="color: #0a2463" name="icon_email" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="password">
            <el-input
              ref="password"
              type="password"
              v-model="registerForm.password"
              placeholder="密码"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon name="icon_lock" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="retype_password">
            <el-input
              type="password"
              v-model="registerForm.retype_password"
              placeholder="确认密码"
              @keyup.enter.native="handleRegister"
            >
              <span slot="prefix" class="svg-container">
                <svg-icon name="icon_lock" />
              </span>
            </el-input>
          </el-form-item>
        </el-col>
        <template v-if="needMsgCode">
          <el-col :span="12">
            <el-form-item prop="sms_verify_code">
              <el-input
                maxlength="6"
                v-model="registerForm.sms_verify_code"
                placeholder="请输入验证码"
              >
                <span slot="prefix" class="svg-container">
                  <svg-icon name="icon_lock" />
                </span>
                <el-button :loading="sending" @click="sendMsg" slot="append">{{
                  sendBtnText
                }}</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </template>
        <el-col :span="12">
          <el-button
            v-waves
            :loading="loading"
            type="primary"
            style="width: 320px;height: 40px"
            @click.native.prevent="handleRegister"
            >注册</el-button
          >
        </el-col>
        <el-col :span="12">
          <div class="color-pr" style="text-align:right">
            <router-link class="register" to="/login">
              <svg-icon name="arrow1" />
              返回登录
            </router-link>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script lang="ts">
/**
 * generate by vscode
 */
import { Component, Vue, Prop } from 'vue-property-decorator'
import { isValidMobile, isValidEmail } from '@/utils/validate'
import { UserModule } from '@/store/modules/user'
import { Form, Message } from 'element-ui'
const WAIT_TIME = process.env.NODE_ENV === 'development' ? 10 : 60
@Component({
  name: 'find-pwd'
})
export default class Register extends Vue {
  @Prop() someProp?: any
  private pwdType = 'password'
  private loading = false
  private tid = 0
  private time = 0
  private sending = false

  private registerForm = {
    username: '',
    name: '',
    mobile: '',
    email: '',
    password: '',
    retype_password: '',
    sms_verify_code: ''
  }

  private validateMobile = (rule: any, value: string, callback: Function) => {
    if (!rule.required) {
      if (!value) {
        return callback()
      }
    }
    if (!isValidMobile(value)) {
      callback(new Error('请输入正确的手机号码'))
    } else {
      callback()
    }
  }

  private validateRetypePassword = (
    rule: any,
    value: string,
    callback: Function
  ) => {
    if (value !== this.registerForm.password) {
      callback(new Error('密码输入不一致'))
    } else {
      callback()
    }
  }

  get loginMethod(): any {
    return UserModule.sysConfig ? UserModule.sysConfig.loginMethods : {}
  }
  get needMsgCode() {
    // return true
    return this.loginMethod.mobile
  }
  get rules() {
    return {
      username: [
        {
          required: this.loginMethod.username,
          trigger: 'blur',
          message: '请输入用户名'
        }
      ],
      name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
      mobile: [
        {
          required: this.loginMethod.mobile,
          validator: this.validateMobile,
          trigger: 'blur'
        }
      ],
      email: [
        {
          required: this.loginMethod.email,
          type: 'email',
          message: '请输入正确的邮箱',
          trigger: ['blur', 'change']
        }
      ],
      password: [
        {
          required: true,
          type: 'string',
          min: 6,
          trigger: 'blur',
          message: '密码至少包含6个字符'
        }
      ],
      retype_password: [
        { validator: this.validateRetypePassword, trigger: 'blur' }
      ],
      sms_verify_code: [
        {
          required: this.needMsgCode,
          message: '请输入6位验证码',
          len: 6
        },
        {
          trigger: 'blur',
          validator(rule: any, value: string, cb: Function) {
            if (/\d{6}/.test(value)) {
              return cb()
            }
            return cb(new Error('请输入6位验证码'))
          }
        }
      ]
    }
  }
  afterRegister() {
    if (this.loginMethod.mobile) {
      return this.$router.replace('/login/success')
    }
    if (this.loginMethod.email) {
      return this.$confirm(
        `激活邮件已发送至您的邮箱${this.registerForm.email}，请前往认证。`,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$router.replace('/login')
      })
    }
    this.$router.replace('/login/success')
  }
  private handleRegister() {
    //@ts-ignore
    const form = this.$refs.registerForm as Form

    form.validate(async (valid: boolean) => {
      if (!valid) {
        return
      }
      this.loading = true
      try {
        await UserModule.Register(this.registerForm)
        this.afterRegister()
      } catch (error) {
        console.error(error)
      }
      this.loading = false
    })
  }
  get sendBtnText() {
    if (this.time !== 0) {
      return WAIT_TIME - this.time + 's'
    }
    return '获取验证码'
  }
  private async sendMsg() {
    const { mobile } = this.registerForm
    if (this.time !== 0 || this.sending) {
      return
    }
    if (!isValidMobile(mobile)) {
      return Message.error('请输入正确的手机号')
    }
    this.sending = true
    await UserModule.GetRegisterMsgCode(mobile)
    this.sending = false
    Message.success('验证码已发送，请注意查收')
    clearInterval(this.tid)
    const fn = () => {
      let t = this.time + 1
      if (t >= WAIT_TIME) {
        t = 0
        clearInterval(this.tid)
      }
      this.time = t
    }
    fn()
    //@ts-ignore
    this.tid = setInterval(fn, 1000)
  }
}
</script>
<style lang="scss">
.register-div {
  width: 660px;
  position: relative;
}
</style>
